import { defineStore } from 'pinia';
import menuOptions from './data/menu';
import Cookie from '@/utils/cookie';
import { GlobalAPI } from '@/app/api';
import { message, notification } from '@/utils/naiveApi';

let token = Cookie.get('token');

export default defineStore('main', {
  state: () => {
    return {
      systemName: '超级萝卜运营管理系统',
      systemNameEn: 'Super Carrot',
      systemComplete: false,
      loginState: !!token,
      theme: 'light',
      layout: 'layout3',
      menu: menuOptions,
      token: token,
      userInfo: null
    };
  },
  actions: {
    login(data) {
      return GlobalAPI.login(data).then(res => {
        if (res.code) {
          message.warning(res.msg);
          return false;
        }
        this.token = res.data.token;
        this.loginState = true;
        this.initSystem();
        Cookie.set('token', res.data.token);
      });
    },
    logout() {
      this.loginState = false;
      this.systemComplete = false;
      this.userInfo = null;
      this.token = '';
      Cookie.remove('token');
    },
    getUserInfo() {
      return GlobalAPI.getUserInfo({ token }).then(res => {
        this.userInfo = res;
      });
    },
    initSystem() {
      return this.getUserInfo().then(() => {
        this.systemComplete = true;
      });
    }
  }
});
